<?php
class CommonUtils
{
	public static function getMongoDB(){
		$config  = ConfigReaderFactory::getInstance()->getConfigReader(AC::CONFIG_FILE)->getConfig();
		$linkurl = (string)$config->mongodb;
		$connect = new Mongo($linkurl,array("persist" => "x"));
		return $connect->pdes->change_log;
	}

	public static function getDbConn($type=0,$destination='db')
	{
		static $conn=array();
		static $target = array("reader","writer");
		static $class = array("ReadableRecordFactory","WritableRecordFactory");

		$config = ConfigReaderFactory::getInstance()->getConfigReader(AC::CONFIG_FILE)->getConfig();
		$db     = $config->$destination;
		$conn_name = $type.$destination;

		if(!isset($conn[$conn_name])){
			$conn[$conn_name] = new $class[$type] ($db->$target[$type],$db->user,(string)$db->pwd,$db->name);
		}
		return $conn[$conn_name];
	}

    public static function getAdminMail($type='default'){
        $config = ConfigReaderFactory::getInstance()->getConfigReader(AC::CONFIG_FILE)->getConfig();
        $mailto = $config->xpath("/config/adminMailList/$type");
        if(isset($mailto[0])){
            return (string)$mailto[0];
        }else{
            return '';
        }
    }

	/**
	 * Generation xml from array
	 */
	public static function arrayToXml($array,$start_tag='ROOT',$layer=0){
		$space = str_repeat("\t",$layer);
		if($start_tag == 'ROOT'){
			$start="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<$start_tag>\n";
		}else{
			$start="$space<$start_tag>\n";
		}
		foreach($array as $key=>$val){
			if(is_numeric($key)) $key = 'item id="'.$key.'"';
			if(is_object($val) || is_array($val)){
				$start .= self::arrayToXml($val,$key,$layer+1);
			}else{
				$key = explode(' ',$key);
				$key = $key[0];
				$start .= "$space\t<$key>$val</$key>\n";
			}
		}
		$start_tag = explode(' ',$start_tag);
		$start_tag = $start_tag[0];
		$start .= "$space</$start_tag>".($layer>0?"\n":'');
		return $start;
	}
}
?>
